﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Natty.NetCore.SqlSuger
{
    public class SqlSugar : IDisposable
    {
        public SqlSugarClient db = null;
        public string ConnectionString = "Data Source=.;Initial Catalog=Blog;Integrated Security=True";
        public SqlSugar()
        {
            if (this.db == null)
            {
                this.db = GetInstance();
            }
        }
        private SqlSugarClient GetInstance()
        {
            if (ConnectionString == null) return null;
            //创建数据库对象
            SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = ConnectionString,//连接符字串
                DbType = DbType.SqlServer,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute//从特性读取主键自增信息
            });

            //添加Sql打印事件，开发中可以删掉这个代码
            //db.Aop.OnLogExecuting = (sql, pars) =>
            //{
            //    Console.WriteLine(sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
            //    Console.WriteLine();
            //};
            return db;
        }

        public void Dispose()
        {
            this.db.Close();
        }

        ~SqlSugar()
        {
            this.Dispose();
        }

    }
}
